package cn.lwx.javaweb.web.action;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

import cn.lwx.javaweb.bean.User;
import cn.lwx.javaweb.utils.UserUtils;

/**
 * 处理用户登录和退出
 *
 * @author lwx
 * @date 2021-05-08
 */
@WebServlet({"/login", "/exit"})
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String servletPath = request.getServletPath();
        if ("/login".equals(servletPath)) {
            doLogin(request, response);
        } else if ("/exit".equals(servletPath)) {
            doExit(request, response);
        }
    }

    private void doLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //判断用户是否有效--业务逻辑
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        boolean flag = UserUtils.isValid(user);

        if (flag) {
            // 获取session对象
            HttpSession session = request.getSession();
            session.setAttribute("user", user);

            String agree = request.getParameter("agree");
            if ("1".equals(agree)) {
                // 创建Cookie对象存储登录名
                Cookie cookie1 = new Cookie("username", username);
                // 创建Cookie对象存储密码
                Cookie cookie2 = new Cookie("password", password); // 有时间的话要进行加密
                // 设置cookie的有效期为十天
                cookie1.setMaxAge(60 * 60 * 24 * 10);
                cookie2.setMaxAge(60 * 60 * 24 * 10);
                // 设置cookie的path（只要访问这个应用，浏览器就一定要携带这两个cookie）
                cookie1.setPath(request.getContextPath());
                cookie2.setPath(request.getContextPath());
                // 响应cookie给浏览器
                response.addCookie(cookie1);
                response.addCookie(cookie2);
            }


            //true 用户及密码有效,登录成功
            response.sendRedirect(request.getContextPath() + "/stu/list");

        } else {
            // 登录失败，跳转到失败页面
            response.sendRedirect(request.getContextPath() + "/fail.jsp");
        }
    }

    private void doExit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取session对象，销毁session
        HttpSession session = request.getSession(false);
        if (session != null) {

            // 从session域中删除user对象
            session.removeAttribute("user");

            // 手动销毁session对象。
            session.invalidate();

            // 销毁cookie（退出系统将所有的cookie全部销毁）
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    // 设置cookie的有效期为0，表示删除该cookie
                    cookie.setMaxAge(0);
                    // 设置一个下cookie的路径
                    cookie.setPath(request.getContextPath());
                    // 响应cookie给浏览器，浏览器端会将之前的cookie覆盖。
                    response.addCookie(cookie);
                }
            }
            // 跳转到欢迎页
            response.sendRedirect(request.getContextPath());
        }
    }
}
